package com.kgis.map.handler.feature.draw
{
	import com.kgis.map.Map;
	import com.kgis.map.common.enum.HandlerEnum;
	import com.kgis.map.common.enum.MapActionEnum;
	import com.kgis.map.common.util.ResourceUtil;
	import com.kgis.map.constant.LayerIdConstants;
	import com.kgis.map.constant.StringConstants;
	import com.kgis.map.control.Blackboard;
	import com.kgis.map.control.RotateAngle;
	import com.kgis.map.cursor.CrossCursor;
	import com.kgis.map.cursor.SnapLineCursor;
	import com.kgis.map.cursor.SnapVertexCursor;
	import com.kgis.map.events.EditEvent;
	import com.kgis.map.feature.Feature;
	import com.kgis.map.geometry.PointGeometry;
	import com.kgis.map.geometry.basetype.Extent;
	import com.kgis.map.geometry.basetype.Location;
	import com.kgis.map.geometry.basetype.Pixel;
	import com.kgis.map.handler.Handler;
	import com.kgis.map.handler.feature.draw.AnchorPoint;
	import com.kgis.map.handler.feature.draw.EditHandler;
	import com.kgis.map.handler.feature.draw.snap.SnapReturn;
	import com.kgis.map.handler.feature.draw.snap.SnapTypeEnum;
	import com.kgis.map.handler.mouse.ClickHandler;
	import com.kgis.map.layer.FeatureLayer;
	import com.kgis.map.layer.GraphicLayer;
	import com.kgis.widgets.managers.ConfirmHelper;
	
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.ui.Keyboard;
	import flash.utils.getTimer;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.events.CloseEvent;
	import mx.managers.CursorManager;
	import mx.managers.PopUpManager;

	[ExcludeClass]
	public class AbstractEditHandler extends Handler
	{
		/**
		 *
		 * 移动设施模式开关，默认为false，用户激活后才可支持移动
		 * */
		protected var MOVE_MODE:Boolean=false;
		/**
		 *
		 * 拖动节点模式开关，默认为false，用户激活后才可支持移动
		 * */
		protected var DRAG_VERTICES_MODE:Boolean=false;
		/**
		 *
		 * 增加节点模式开关，默认为false，用户激活后才可支持移动
		 * */
		protected var ADD_VERTICES_MODE:Boolean=false;
		/**
		 * 删除节点模式开关，取消以前的delete快捷键
		 * */
		protected var DELETE_VERTICES_MODE:Boolean=false
		/**
		 *
		 * 旋转模式开关，默认为false，用户激活后才可支持移动
		 * */
		protected var ROTATE_MODE:Boolean=false;
		/**
		 * 关联移动，仅限于编辑设施为点
		 * */
		protected var MOVE_ASSOCIATED_MODE:Boolean=false;
		/**
		 * 高亮的节点，可删除
		 * */
		protected var deleteAnchor:AnchorPoint=null;
		/**
		 * 正在编辑的节点
		 * */
		protected var editAnchor:AnchorPoint=null;
		/**
		 * 标记是否正在移动编辑节点过程中
		 * */
		protected var bIsAnchorMove:Boolean=false;
		/**
		 * 标记此锚点是否第一次点击，为了区分出锚点与map的mouseup事件
		 * */
		protected var bIsFirstAnchor:Boolean=true;
		/**
		 * 与pointUp配套使用，标记是鼠标点击还是拖动地图
		 * 鼠标点击下去的位置，拖动地图时，map的mouseX，mouseY在变。layer的mouseX与mouseY不变
		 * */
		protected var pointDown:PointGeometry;
		/**
		 * 与pointDown配套使用，标记是鼠标点击还是拖动地图
		 * 鼠标点击下去的位置，拖动地图时，map的mouseX，mouseY在变。layer的mouseX与mouseY不变
		 * */
		protected var pointUp:PointGeometry;

		/**
		 * 移动模式开关，ctrl快捷键打开，ESC快捷键关闭
		 * */
		protected var isFeatureMove:Boolean=false;
		/**
		 * 标记是否正在移动设施过程中
		 * */
		protected var isFeatureMoving:Boolean=false; //正在移动中
		/**
		 * 移动设施起始点，当用户按ESC回退时，设施返回到起始点位置
		 * */
		protected var moveStartPoint:Location=null;
		protected var moveEndPoint:Location=null;
		protected var moveStartPiexl:Pixel=null;
		protected var moveEndPiexl:Pixel=null;


		/**
		 * 编辑模式<br>
		 * 0: 一种首尾端只有一条线<br>
		 * 1:另一种在中间，同时画两条线<br>
		 * 2：移动地图模式<br>
		 * 100: 默认模式，鼠标移到feature上，插入节点<br>
		 * */
		protected var editMode:int=100;
		/**
		 * editMode100下鼠标在feature上创建的节点
		 * */
		protected var createPoint:PointGeometry=null;

		/**
		 * 拖动节点时，两个相应的点地图坐标与像素坐标
		 *
		 * */
		protected var editingPoint1:PointGeometry=null;
		protected var editingPoint2:PointGeometry=null;
		//对应的像素点
		protected var _startPoint1:Pixel=new Pixel();
		protected var _startPoint2:Pixel=new Pixel();
		//关联移动的所有feature
		protected var moveFeatures:ArrayCollection;

		//标识  mouse在down拖动地图中 还是其它
		protected var isMouseDowning:Boolean=false;
		private var _editFeature:Feature=null;
		protected var _clickHandler:ClickHandler=null;
		protected var _drawContainer:FeatureLayer=null;

		//可捕捉的图层ids
		private var _snapLayerIds:ArrayCollection;
		private var _snapLayers:Vector.<FeatureLayer>;
		//容差默认4个像素为单位，
		private var _snapTolerance:Number=4;
		protected var snapReturn:SnapReturn;

		private var _snapClickCallback:Function=null;
		public var blackBoard:Blackboard;
		protected var rotateAngle:RotateAngle;
		
		

		public function AbstractEditHandler(map:Map, handlername:String)
		{
			super(map, handlername);
			this._clickHandler=new ClickHandler(map, HandlerEnum.CLICK_HANDLER)
		}

		public function activateEditMode(editType:Number=EditHandler.MOVE):void
		{
			map.operateMode=MapActionEnum.MAP_EDIT;

			if ((editType & EditHandler.MOVE) == EditHandler.MOVE)
			{
				this.MOVE_MODE=true;
			}
			if ((editType & EditHandler.DRAG_VERTICES) == EditHandler.DRAG_VERTICES)
			{
				this.DRAG_VERTICES_MODE=true;
			}
			if ((editType & EditHandler.ADD_VERTICES) == EditHandler.ADD_VERTICES)
			{
				this.ADD_VERTICES_MODE=true;
			}
			if ((editType & EditHandler.ROTATE) == EditHandler.ROTATE)
			{
				this.ROTATE_MODE=true;
				if (ROTATE_MODE)
				{
					//弹出对话框，输入角度
					rotateAngle=new RotateAngle();
					rotateAngle.call=rotateAngleHandler;
					var location:Point=map.localToGlobal(new Point(0, map.height - 140));
					rotateAngle.x=location.x;
					rotateAngle.y=location.y;
					PopUpManager.addPopUp(rotateAngle, map, false);
						//   PopUpManager.centerPopUp(rotateAngle);
				}
			}
			if ((editType & EditHandler.DELETE_VERTICES) == EditHandler.DELETE_VERTICES)
			{
				this.DELETE_VERTICES_MODE=true;
			}
			if ((editType & EditHandler.MOVE_ASSOCIATED) == EditHandler.MOVE_ASSOCIATED)
			{
				this.MOVE_ASSOCIATED_MODE=true;
			}
			if (this.map)
			{
				this.map.addEventListener(EditEvent.FEATURE_DELETED, featureDeleteHandler);
			}

		}

		protected function rotateAngleHandler():void
		{

		}

		//关闭某一操作模式
		public function deactivateEditMode(editType:Number):void
		{

			if ((editType & EditHandler.MOVE) == EditHandler.MOVE)
			{
				this.MOVE_MODE=false;
			}
			if ((editType & EditHandler.DRAG_VERTICES) == EditHandler.DRAG_VERTICES)
			{
				this.DRAG_VERTICES_MODE=false;
			}
			if ((editType & EditHandler.ADD_VERTICES) == EditHandler.ADD_VERTICES)
			{
				this.ADD_VERTICES_MODE=false;
			}
			if ((editType & EditHandler.ROTATE) == EditHandler.ROTATE)
			{
				this.ROTATE_MODE=false;
				PopUpManager.removePopUp(rotateAngle);
				rotateAngle=null;
			}
			if ((editType & EditHandler.DELETE_VERTICES) == EditHandler.DELETE_VERTICES)
			{
				this.DELETE_VERTICES_MODE=false;
			}
			if ((editType & EditHandler.MOVE_ASSOCIATED) == EditHandler.MOVE_ASSOCIATED)
			{
				this.MOVE_ASSOCIATED_MODE=false;
			}
		}

		private function featureDeleteHandler(event:EditEvent):void
		{
			if (event.editFeature == this.editFeature && this.editFeature.editing)
			{
				initialize();
			}
		}

		public function get editFeature():Feature
		{
			return _editFeature;
		}

		public function set editFeature(value:Feature):void
		{
			_editFeature=value;
			this.editFeature.editing=true;
			this.editFeature.executeDrawing();
		}

		protected function mouseDblClick(Lastpx:Pixel, features:Vector.<Feature>, event:MouseEvent):void
		{
			//双击空白处结束编辑事件抛出编辑feature
			//关联移动时将所有相关的feature全部抛出
			if (MOVE_ASSOCIATED_MODE)
			{
				this.map.dispatchEvent(new EditEvent(EditEvent.GEOMETRY_EDITEND, editFeature, null, moveFeatures));
			}
			else if (features.length == 0 || features[0] == editFeature)
			{
				this.map.dispatchEvent(new EditEvent(EditEvent.GEOMETRY_EDITEND, editFeature));
			}
			initialize();
		}
		protected function keyDownHandler(event:KeyboardEvent):void {
			if(Keyboard.ESCAPE){
				this.map.dispatchEvent(new EditEvent(EditEvent.GEOMETRY_EDITEND, null));
				map.clearHighLight();
				initialize();
			}
		}
		override public function set map(value:com.kgis.map.Map):void
		{
			if (value != null)
			{
				super.map=value;
			}
		}

		/**
		 * 捕获设施的回调函数，抛出捕捉到的feature，及捕获点坐标
		 *
		 * */
		public function get snapClickCallback():Function
		{
			return _snapClickCallback;
		}

		public function set snapClickCallback(value:Function):void
		{
			_snapClickCallback=value;
		}

		public function get snapTolerance():Number
		{
			return _snapTolerance;
		}

		/**
		 * 捕捉容差，以像素为单位，建议不要设置采用默认容差值
		 * */
		public function set snapTolerance(value:Number):void
		{
			_snapTolerance=value;
		}

		public function get snapLayers():Vector.<FeatureLayer>
		{
			if (_snapLayers == null)
			{
				_snapLayers=new Vector.<FeatureLayer>();
			}
			return _snapLayers;
		}

		public function set snapLayers(value:Vector.<FeatureLayer>):void
		{
			_snapLayers=value;
		}

		public function get snapLayerIds():ArrayCollection
		{
			return _snapLayerIds;
		}

		public function set snapLayerIds(value:ArrayCollection):void
		{
			_snapLayerIds=value;
			if (value != null && value.length > 0)
			{
				_snapLayers=null;
				for each (var layerId:int in _snapLayerIds)
				{
					if (map.getLayerById(layerId) != null)
					{
						snapLayers.push(map.getLayerById(layerId) as FeatureLayer);
					}

				}
			}
		}

		//初始化到编辑模式最原始的状态，清除上一次编辑保存的状态
		override public function initialize():void
		{
			this.active=false;
			this.editFeature.editing=false;
			this.editFeature.selected=false;
			this.editFeature.executeDrawing();
			this.map.operateMode=MapActionEnum.MAP_PAN;

			snapLayers=null;
			editMode=100;
			isFeatureMove=false;
			isFeatureMoving=false;
			bIsFirstAnchor=true;
			isMouseDowning=false;
			bIsAnchorMove=false;
			//编辑模式
			this.MOVE_MODE=false;
			this.DRAG_VERTICES_MODE=false;
			this.ADD_VERTICES_MODE=false;
			this.DELETE_VERTICES_MODE=false;

			this.ROTATE_MODE=false;
			this.MOVE_ASSOCIATED_MODE=false;

			PopUpManager.removePopUp(rotateAngle);
			rotateAngle=null;
			moveFeatures=null;

		}

		protected function keyboardDown(event:KeyboardEvent):void
		{
			switch (event.keyCode)
			{
				case Keyboard.CONTROL:
//                    if (MOVE_MODE) {
//                        isFeatureMove = true; //打开移动设施
//                    }
//                    //	this.blackBoard.setInfo("移动模式打开");
//                    break;
				case Keyboard.ESCAPE: //关闭移动设施
//                    if (MOVE_MODE) {
//                        isFeatureMove = false;
//                    }
//                    //	this.blackBoard.setInfo("移动模式关闭");
//                    break;
				case Keyboard.DELETE:
					if (DELETE_VERTICES_MODE)
					{
						deleteVertex(); //删除节点
					}
					break;

			}
		}

		//删除选中节点
		protected function deleteVertex():void
		{
			if (deleteAnchor != null)
			{
				var deletePoint:PointGeometry=deleteAnchor.geoPoint;
				ConfirmHelper.showConfirmDialog("", ResourceUtil.getString(StringConstants.DELETE_VERTEX_CONFIRM), function(evt:CloseEvent):void
				{
					if (evt.detail == Alert.YES)
					{
						var anchorLayer:GraphicLayer=map.getLayerById(LayerIdConstants.ANCHORLAYER_LAYERID) as GraphicLayer;
						anchorLayer.removeAnchor();
						editFeature.geometry.removePoint(deletePoint);
						editFeature.executeDrawing();
					}
					else
					{
						return;
					}
				});
			}
		}

		//删除节点
		protected function vertexMouseOver(event:EditEvent):void
		{
			if (DELETE_VERTICES_MODE)
			{
				deleteAnchor=event.anchorPoint;
			}
		}

		protected function vertexMouseOut(event:EditEvent):void
		{
			if (deleteAnchor)
			{
				deleteAnchor=null;
			}
		}

		protected function mouseMoveSnapHandler(event:MouseEvent):void
		{
			if (!snapLayers || snapLayers.length == 0){
				return;
			}
			var pixel:Pixel=new Pixel(_drawContainer.mouseX, _drawContainer.mouseY);
			var lonlat:Location=this.map.getLocationFromLayerPx(pixel);
			var mousePoint:PointGeometry=new PointGeometry(lonlat.x, lonlat.y);
			var distance:Number=map.resolution * snapTolerance;
			var snapPoint:PointGeometry=new PointGeometry;
			snapReturn=new SnapReturn();
			map.clearHighLight();
			var originExtent:Extent;
			var flag:int=-1;

//			var starttime:Date = new Date();
			for each (var layer:FeatureLayer in snapLayers){
				originExtent=new Extent(mousePoint.x - distance, mousePoint.y - distance, mousePoint.x + distance, mousePoint.y + distance);
				for (var i:int=0; i < layer.features.length; i++)
				{
					var feature:Feature=layer.features[i];
					if (feature.geometry.getExtent().intersectsBounds(originExtent, true))
					{
						//计算点与feature各个节点的距离
						snapReturn.snapType=feature.geometry.getTolerancePoint(mousePoint, distance, snapPoint);
						if (snapReturn.snapType != SnapTypeEnum.NO_SNAPS){
							snapReturn.snapPoint=snapPoint;
							snapReturn.snapFeature=feature;
							snapReturn.snapFeatures.addItem(feature);
							//设置高亮绿色，表明被捕捉设施。
							feature.highLighted=true;
						}
					}
				}
			}
//			trace("timer:-----------------" + ((new Date()).getTime() - starttime.getTime()).toString());
			switch (snapReturn.snapType)
			{
				case SnapTypeEnum.SNAP_OVERTEX:
					if (flag != SnapTypeEnum.SNAP_OVERTEX)
					{
						CursorManager.removeAllCursors();
						CursorManager.setCursor(SnapVertexCursor);
						flag=SnapTypeEnum.SNAP_OVERTEX
					}
					break;
				case SnapTypeEnum.SNAP_INLINE:
					if (flag != SnapTypeEnum.SNAP_INLINE)
					{
						CursorManager.removeAllCursors();
						CursorManager.setCursor(SnapLineCursor);
						flag=SnapTypeEnum.SNAP_INLINE
					}
					break;
				case SnapTypeEnum.NO_SNAPS:
					if (flag != SnapTypeEnum.NO_SNAPS)
					{
						CursorManager.removeAllCursors();
						CursorManager.setCursor(CrossCursor);
						flag=SnapTypeEnum.NO_SNAPS
					}
                        snapReturn = null;
			}
		}

	}
}
